
<!DOCTYPE HTML>
<html lang="" >
    <head>
        <meta charset="UTF-8">
        <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
        <title>async_await · GitBook</title>
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="description" content="">
        <meta name="generator" content="GitBook 3.2.3">
        
        
        
    
    <link rel="stylesheet" href="gitbook/style.css">

    
            
                
                <link rel="stylesheet" href="gitbook/gitbook-plugin-highlight/website.css">
                
            
                
                <link rel="stylesheet" href="gitbook/gitbook-plugin-search/search.css">
                
            
                
                <link rel="stylesheet" href="gitbook/gitbook-plugin-fontsettings/website.css">
                
            
        

    

    
        
    
        
    
        
    
        
    
        
    
        
    

        
    
    
    <meta name="HandheldFriendly" content="true"/>
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <link rel="apple-touch-icon-precomposed" sizes="152x152" href="gitbook/images/apple-touch-icon-precomposed-152.png">
    <link rel="shortcut icon" href="gitbook/images/favicon.ico" type="image/x-icon">

    
    <link rel="next" href="Set和WeakSet.html" />
    
    
    <link rel="prev" href="Symbol和generator.html" />
    

    </head>
    <body>
        
<div class="book">
    <div class="book-summary">
        
            
<div id="book-search-input" role="search">
    <input type="text" placeholder="Type to search" />
</div>

            
                <nav role="navigation">
                


<ul class="summary">
    
    

    

    
        
        
    
        <li class="chapter " data-level="1.1" data-path="./">
            
                <a href="./">
            
                    
                    Introduction
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.2" data-path="变量.html">
            
                <a href="变量.html">
            
                    
                    变量
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.3" data-path="解构.html">
            
                <a href="解构.html">
            
                    
                    解构
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.4" data-path="字符串.html">
            
                <a href="字符串.html">
            
                    
                    字符串
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5" data-path="函数.html">
            
                <a href="函数.html">
            
                    
                    函数
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.6" data-path="数组.html">
            
                <a href="数组.html">
            
                    
                    数组
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.7" data-path="对象.html">
            
                <a href="对象.html">
            
                    
                    对象
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.8" data-path="prototype.html">
            
                <a href="prototype.html">
            
                    
                    prototype
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.9" data-path="Promise.html">
            
                <a href="Promise.html">
            
                    
                    Promise
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.10" data-path="模块化.html">
            
                <a href="模块化.html">
            
                    
                    模块化
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.11" data-path="class和继承.html">
            
                <a href="class和继承.html">
            
                    
                    class和继承
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.12" data-path="this.html">
            
                <a href="this.html">
            
                    
                    this
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.13" data-path="Symbol和generator.html">
            
                <a href="Symbol和generator.html">
            
                    
                    Symbol和generator
            
                </a>
            

            
        </li>
    
        <li class="chapter active" data-level="1.14" data-path="async_await.html">
            
                <a href="async_await.html">
            
                    
                    async_await
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.15" data-path="Set和WeakSet.html">
            
                <a href="Set和WeakSet.html">
            
                    
                    Set和WeakSet
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.16" data-path="Map和WeakMap.html">
            
                <a href="Map和WeakMap.html">
            
                    
                    Map和WeakMap
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.17" data-path="数字和Math.html">
            
                <a href="数字和Math.html">
            
                    
                    数字和Math
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.18" data-path="正则.html">
            
                <a href="正则.html">
            
                    
                    正则
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.19" data-path="Proxy.html">
            
                <a href="Proxy.html">
            
                    
                    Proxy
            
                </a>
            

            
        </li>
    

    

    <li class="divider"></li>

    <li>
        <a href="https://www.gitbook.com" target="blank" class="gitbook-link">
            Published with GitBook
        </a>
    </li>
</ul>


                </nav>
            
        
    </div>

    <div class="book-body">
        
            <div class="body-inner">
                
                    

<div class="book-header" role="navigation">
    

    <!-- Title -->
    <h1>
        <i class="fa fa-circle-o-notch fa-spin"></i>
        <a href="." >async_await</a>
    </h1>
</div>




                    <div class="page-wrapper" tabindex="-1" role="main">
                        <div class="page-inner">
                            
<div id="book-search-results">
    <div class="search-noresults">
    
                                <section class="normal markdown-section">
                                
                                <h1 id="asyncawait">async_await</h1>
<p>&#x5173;&#x4E8E;&#x5F02;&#x6B65;,&#x89E3;&#x51B3;&#x65B9;&#x6848;:  </p>
<ol>
<li>&#x56DE;&#x8C03;&#x51FD;&#x6570;</li>
<li>&#x4E8B;&#x4EF6;&#x76D1;&#x542C;</li>
<li>&#x53D1;&#x5E03;/&#x8BA2;&#x9605;</li>
<li>generator</li>
<li>Promise</li>
<li>async (&#x4F18;&#x96C5;)</li>
</ol>
<h3 id="promise-&#x793A;&#x4F8B;">Promise &#x793A;&#x4F8B;</h3>
<pre><code class="lang-js"><span class="hljs-comment">// &#x5F15;&#x5165; node js &#x7684; fs</span>
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">&apos;fs&apos;</span>);

<span class="hljs-keyword">const</span> readFile = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">fileName</span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>((resolve, reject) =&gt; {
        fs.readFile(fileName, (err, data) =&gt; {
            <span class="hljs-keyword">if</span> (err) reject(err);
            resolve(data);
        });
    });
}
</code></pre>
<pre><code class="lang-js">readFile(<span class="hljs-string">&apos;1.txt&apos;</span>).then(res=&gt;{
    <span class="hljs-built_in">console</span>.log(res.toString());
    <span class="hljs-keyword">return</span> readFile(<span class="hljs-string">&apos;2.txt&apos;</span>);
}).then(res=&gt;{
    <span class="hljs-built_in">console</span>.log(res.toString());
    <span class="hljs-keyword">return</span> readFile(<span class="hljs-string">&apos;3.txt&apos;</span>);
}).then(res=&gt;{
    <span class="hljs-built_in">console</span>.log(res.toString());
});
<span class="hljs-comment">// &#x6267;&#x884C;: node xxx.js</span>
</code></pre>
<h3 id="generator-&#x793A;&#x4F8B;">generator &#x793A;&#x4F8B;</h3>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> * <span class="hljs-title">gen</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">yield</span> readFile(<span class="hljs-string">&apos;1.txt&apos;</span>);
    <span class="hljs-keyword">yield</span> readFile(<span class="hljs-string">&apos;2.txt&apos;</span>);
    <span class="hljs-keyword">yield</span> readFile(<span class="hljs-string">&apos;3.txt&apos;</span>);
}

<span class="hljs-keyword">let</span> g1 = gen();
g1.next().value.then(res=&gt;{
    <span class="hljs-built_in">console</span>.log(res.toString());
    <span class="hljs-keyword">return</span> g1.next().value;
}).then(res=&gt;{
    <span class="hljs-built_in">console</span>.log(res.toString());
    <span class="hljs-keyword">return</span> g1.next().value;
}).then(res=&gt;{
    <span class="hljs-built_in">console</span>.log(res.toString());
});
</code></pre>
<h3 id="async-&#x793A;&#x4F8B;">async &#x793A;&#x4F8B;</h3>
<pre><code class="lang-js"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fn</span>(<span class="hljs-params"></span>) </span>{ <span class="hljs-comment">//async&#x8868;&#x793A;&#x5F02;&#x6B65;,&#x8FD9;&#x4E2A;&#x51FD;&#x6570;&#x91CC;&#x9762;&#x6709;&#x5F02;&#x6B65;&#x4EFB;&#x52A1;</span>
    <span class="hljs-keyword">let</span> f1 = <span class="hljs-keyword">await</span> readFile(<span class="hljs-string">&apos;1.txt&apos;</span>);
    <span class="hljs-built_in">console</span>.log(f1.toString());
    <span class="hljs-keyword">let</span> f2 = <span class="hljs-keyword">await</span> readFile(<span class="hljs-string">&apos;2.txt&apos;</span>);
    <span class="hljs-built_in">console</span>.log(f2.toString());
    <span class="hljs-keyword">let</span> f3 = <span class="hljs-keyword">await</span> readFile(<span class="hljs-string">&apos;3.txt&apos;</span>);
    <span class="hljs-built_in">console</span>.log(f3.toString());
}

fn(); <span class="hljs-comment">// fn() &#x6267;&#x884C;&#x7ED3;&#x679C;&#x662F;&#x4E00;&#x4E2A;Promise</span>
</code></pre>
<p>async&#x7279;&#x70B9;:</p>
<ol>
<li>await&#x53EA;&#x80FD;&#x653E;&#x5230;async&#x51FD;&#x6570;&#x4E2D;</li>
<li>&#x76F8;&#x6BD4;generator&#x8BED;&#x4E49;&#x5316;&#x66F4;&#x5F3A;</li>
<li>await&#x540E;&#x9762;&#x53EF;&#x4EE5;&#x662F;Promise&#x5BF9;&#x8C61;, &#x4E5F;&#x53EF;&#x4EE5;&#x662F;&#x6570;&#x5B57;, &#x5B57;&#x7B26;&#x4E32;, &#x5E03;&#x5C14;...</li>
<li>async&#x51FD;&#x6570;&#x8FD4;&#x56DE;&#x7684;&#x662F;&#x4E00;&#x4E2A;Promise&#x5BF9;&#x8C61;</li>
<li>&#x5982;&#x679C;await&#x8BED;&#x53E5;&#x540E;&#x9762;&#x662F;Promise, &#x4E14;&#x72B6;&#x6001;&#x662F;reject, &#x5219;&#x6574;&#x4E2A;async&#x51FD;&#x6570;&#x4F1A;&#x4E2D;&#x65AD;&#x6267;&#x884C;</li>
</ol>
<pre><code class="lang-js">&lt;script&gt;
  async function fn() {
      throw new Error(&quot;Error 404&quot;);
  }
  fn().then(res =&gt; {
      console.log(res); //welcome
  }).catch(err =&gt; {
      console.log(err);
  })
&lt;/script&gt;
</code></pre>
<p>&#x5982;&#x679C;await&#x8BED;&#x53E5;&#x540E;&#x9762;&#x662F;Promise, &#x4E14;&#x72B6;&#x6001;&#x662F;reject, &#x5219;&#x6574;&#x4E2A;async&#x51FD;&#x6570;&#x4F1A;&#x4E2D;&#x65AD;&#x6267;&#x884C;, &#x793A;&#x4F8B;:</p>
<pre><code class="lang-js">&lt;script&gt;
  async function fn() {
      await Promise.resolve(&apos;1&apos;);
      await Promise.reject(&apos;&#x51FA;&#x73B0;&#x95EE;&#x9898;&apos;);
      await Promise.resolve(&apos;2&apos;);
  }
  fn().then(res=&gt;{
      console.log(res);
  }).catch(err=&gt;{
      console.log(err); //&#x6253;&#x5370;&#x4E86;: &#x51FA;&#x73B0;&#x95EE;&#x9898;
  })
&lt;/script&gt;
</code></pre>
<p>&#x53EF;&#x4EE5;&#x4F7F;&#x7528; try-catch &#x4E0D;&#x8BA9;&#x5B83;&#x4E2D;&#x65AD;:</p>
<pre><code class="lang-js">&lt;script&gt;
  async function fn() {
      await Promise.resolve(&apos;1&apos;);
      try {
          await Promise.reject(&apos;&#x51FA;&#x73B0;&#x95EE;&#x9898;&apos;);
      } catch (e) {

      }
      return await Promise.resolve(&apos;2&apos;);
  }
  fn().then(res=&gt;{
      console.log(res); //2
  }).catch(err=&gt;{
      console.log(err);
  })
&lt;/script&gt;
</code></pre>
<p>&#x6216;&#x8005;&#x8BA9;Promise catch</p>
<pre><code class="lang-js">&lt;script&gt;
  async function fn() {
      await Promise.resolve(&apos;1&apos;);
      await Promise.reject(&apos;&#x51FA;&#x73B0;&#x95EE;&#x9898;&apos;).catch(err=&gt;{
          console.log(err);
      });
      return await Promise.resolve(&apos;2&apos;);
  }
  fn().then(res=&gt;{
      console.log(res); //2
  }).catch(err=&gt;{
      console.log(err);
  })
&lt;/script&gt;
</code></pre>
<p>&#x5EFA;&#x8BAE;&#x5728;&#x6240;&#x6709; await &#x7684;&#x5730;&#x65B9;&#x90FD;&#x52A0;&#x4E0A;try-catch</p>
<h3 id="&#x518D;&#x770B;&#x4E00;&#x4E2A;&#x793A;&#x4F8B;">&#x518D;&#x770B;&#x4E00;&#x4E2A;&#x793A;&#x4F8B;</h3>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">&apos;fs&apos;</span>);

<span class="hljs-keyword">const</span> readFile = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">fileName</span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>((resolve, reject) =&gt; {
        fs.readFile(fileName, (err, data) =&gt; {
            <span class="hljs-keyword">if</span> (err) reject(err);
            resolve(data);
        });
    });
}

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fn</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">let</span> [a,b,c] = <span class="hljs-keyword">await</span> <span class="hljs-built_in">Promise</span>.all([
        readFile(<span class="hljs-string">&apos;1.txt&apos;</span>),
        readFile(<span class="hljs-string">&apos;2.txt&apos;</span>),
        readFile(<span class="hljs-string">&apos;3.txt&apos;</span>)
    ]);

    <span class="hljs-built_in">console</span>.log(a.toString());
    <span class="hljs-built_in">console</span>.log(b.toString());
    <span class="hljs-built_in">console</span>.log(c.toString());
}

fn();

<span class="hljs-comment">// node xxx.js</span>
</code></pre>

                                
                                </section>
                            
    </div>
    <div class="search-results">
        <div class="has-results">
            
            <h1 class="search-results-title"><span class='search-results-count'></span> results matching "<span class='search-query'></span>"</h1>
            <ul class="search-results-list"></ul>
            
        </div>
        <div class="no-results">
            
            <h1 class="search-results-title">No results matching "<span class='search-query'></span>"</h1>
            
        </div>
    </div>
</div>

                        </div>
                    </div>
                
            </div>

            
                
                <a href="Symbol和generator.html" class="navigation navigation-prev " aria-label="Previous page: Symbol和generator">
                    <i class="fa fa-angle-left"></i>
                </a>
                
                
                <a href="Set和WeakSet.html" class="navigation navigation-next " aria-label="Next page: Set和WeakSet">
                    <i class="fa fa-angle-right"></i>
                </a>
                
            
        
    </div>

    <script>
        var gitbook = gitbook || [];
        gitbook.push(function() {
            gitbook.page.hasChanged({"page":{"title":"async_await","level":"1.14","depth":1,"next":{"title":"Set和WeakSet","level":"1.15","depth":1,"path":"Set和WeakSet.md","ref":"Set和WeakSet.md","articles":[]},"previous":{"title":"Symbol和generator","level":"1.13","depth":1,"path":"Symbol和generator.md","ref":"Symbol和generator.md","articles":[]},"dir":"ltr"},"config":{"gitbook":"*","theme":"default","variables":{},"plugins":["livereload"],"pluginsConfig":{"livereload":{},"highlight":{},"search":{},"lunr":{"maxIndexSize":1000000,"ignoreSpecialCharacters":false},"sharing":{"facebook":true,"twitter":true,"google":false,"weibo":false,"instapaper":false,"vk":false,"all":["facebook","google","twitter","weibo","instapaper"]},"fontsettings":{"theme":"white","family":"sans","size":2},"theme-default":{"styles":{"website":"styles/website.css","pdf":"styles/pdf.css","epub":"styles/epub.css","mobi":"styles/mobi.css","ebook":"styles/ebook.css","print":"styles/print.css"},"showLevel":false}},"structure":{"langs":"LANGS.md","readme":"README.md","glossary":"GLOSSARY.md","summary":"SUMMARY.md"},"pdf":{"pageNumbers":true,"fontSize":12,"fontFamily":"Arial","paperSize":"a4","chapterMark":"pagebreak","pageBreaksBefore":"/","margin":{"right":62,"left":62,"top":56,"bottom":56}},"styles":{"website":"styles/website.css","pdf":"styles/pdf.css","epub":"styles/epub.css","mobi":"styles/mobi.css","ebook":"styles/ebook.css","print":"styles/print.css"}},"file":{"path":"async_await.md","mtime":"2021-12-19T16:47:03.447Z","type":"markdown"},"gitbook":{"version":"3.2.3","time":"2022-02-17T15:54:39.156Z"},"basePath":".","book":{"language":""}});
        });
    </script>
</div>

        
    <script src="gitbook/gitbook.js"></script>
    <script src="gitbook/theme.js"></script>
    
        
        <script src="gitbook/gitbook-plugin-livereload/plugin.js"></script>
        
    
        
        <script src="gitbook/gitbook-plugin-search/search-engine.js"></script>
        
    
        
        <script src="gitbook/gitbook-plugin-search/search.js"></script>
        
    
        
        <script src="gitbook/gitbook-plugin-lunr/lunr.min.js"></script>
        
    
        
        <script src="gitbook/gitbook-plugin-lunr/search-lunr.js"></script>
        
    
        
        <script src="gitbook/gitbook-plugin-sharing/buttons.js"></script>
        
    
        
        <script src="gitbook/gitbook-plugin-fontsettings/fontsettings.js"></script>
        
    

    </body>
</html>

